package com.zyx.sercurity.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

@Configuration
public class SecurityConfig2 extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;
    //注入数据源
    @Autowired
    private DataSource dataSource;

    //配置对象
    @Bean
    public PersistentTokenRepository persistentTokenRepository() {

        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        return jdbcTokenRepository;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(password());
    }

    @Bean
    PasswordEncoder password() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //配置没有权限访问跳转页面
        http.exceptionHandling().accessDeniedPage("/unauth.html");


        http.formLogin() //自定义自己登录的界面
                .loginPage("/login.html") //登录界面设置
                .loginProcessingUrl("/user/login") //登录访问的路径
                .defaultSuccessUrl("/t  est/index").permitAll()  //登录成功后，跳转路径
                .and().authorizeRequests()
                .antMatchers("/", "/test/hello", "/user/login").permitAll() //设置哪些路径可以直接访问
                .antMatchers("/test/index").hasAuthority("admins") //单个权限
//                .antMatchers("/test/index").hasAnyAuthority("admins,manager") //多个权限
//                .antMatchers("/text/index").hasRole("role")  //单个角色
//                .antMatchers("/text/index").hasAnyRole("role,admin")  //多个角色
                .anyRequest().authenticated()
                .and().rememberMe().tokenRepository(persistentTokenRepository())
                .tokenValiditySeconds(60) //设置有效时长，秒
                .userDetailsService(userDetailsService)
                .and().csrf().disable(); // 关闭csrf防护  csrf跨站请求伪造  会针对PATCH ，POST，PUT，DELETE进行保护
    }
}
